package boot.spring.controller;

import boot.spring.po.Picture;
import com.mongodb.DBCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/*mongoTemplate 使用*/
@Controller
@RequestMapping(value="/templateDemo")
public class DemoController {

    @Autowired
    MongoTemplate mongoTemplate;

    @RequestMapping(value="save",method= RequestMethod.GET)
    @ResponseBody
    public void save(){
        Picture p = new Picture();
        p.setFilename("测试文件");
        // p.setId("123123123");  // 不指定id 则数据库自动生成
        p.setPath("D://P/"+System.currentTimeMillis());
        p.setSize(1024L);
        mongoTemplate.save(p); //id 存在则修改
       // mongoTemplate.createCollection("mycoll");
        System.out.println(mongoTemplate.collectionExists("mycoll"));
        DBCollection dbCollection = mongoTemplate.getCollection("mycoll");
        mongoTemplate.insert(p,"mycoll");
    }
    @RequestMapping(value="find",method= RequestMethod.GET)
    @ResponseBody
    public void find(){
        List<Picture> list =  mongoTemplate.findAll(Picture.class);
        System.out.println(list);
        // 从指定集合中查询
        List<Picture> listmycoll = mongoTemplate.findAll(Picture.class,"mycoll");
        System.out.println(listmycoll);
        Picture p = mongoTemplate.findById("123123123",Picture.class);
        Picture pq = mongoTemplate.findById("60f526bbf4b1f347a80e4300",Picture.class);
        System.out.println(p);
        System.out.println(pq);
        Query query = new Query(Criteria.where("filename").is("测试文件"));
        List<Picture> list2 = mongoTemplate.find(query,Picture.class);
        System.out.println(list2);
        Picture p2 = mongoTemplate.findOne(query,Picture.class);
        System.out.println(p2);

    }

    @RequestMapping(value="del",method= RequestMethod.GET)
    @ResponseBody
    public void del(){
        Picture p = new Picture();
        p.setPath("D://P/1626680484513");
        mongoTemplate.remove(p);
        Query query = new Query(Criteria.where("filename").is("测试文件"));
        mongoTemplate.remove(query,Picture.class);
        mongoTemplate.dropCollection("picture");
    }
}
